package com.xltx.wechat.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xltx.wechat.common.constant.WechatConstant;
import com.xltx.wechat.common.utils.HttpRequest;
import com.xltx.wechat.properties.WechatProperties;
import com.xltx.wechat.service.WechatTemplateMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author liuyc
 * @ClassName WechatTemplateMessageServiceImpl
 * @Description 模板消息实现类
 * @Date 2022/3/16 10:10
 */
@Service
public class WechatTemplateMessageServiceImpl implements WechatTemplateMessageService {

    @Resource
    private WechatProperties wechatProperties;

    public String getToken() {
        String url = WechatConstant.TOKEN.replace("APPID", wechatProperties.getAppId()).replace("APPSECRET", wechatProperties.getAppSecret());
        String accessToken = HttpUtil.get(url);
        JSONObject object = JSONUtil.parseObj(accessToken);
        return object.getStr("access_token");
    }

    @Override
    public String sendNotice(String sendContent) {
        if (StringUtils.isBlank(sendContent)){
            throw new NullPointerException("send content is null");
        }
        String url = WechatConstant.TEMPLATE_MESSAGE.replace("ACCESS_TOKEN", getToken());
        return HttpRequest.sendPost(url, sendContent);
    }
}
